import UrlParse from 'url-parse'
import get from 'lodash/get'

export function formatURL(url: string, pathParam: unknown): string {
  return url.replace(/:(\w+):/g, (match: string, holder: string) => {
    return (get(pathParam, holder) as string) || match
  })
}

/**
 * 返回url的host, 不带协议
 * @param siteOrigin original site
 */
export function getSite(siteOrigin: string): string {
  if (!siteOrigin) {
    return ''
  }
  if (!siteOrigin.startsWith('http')) {
    // tslint:disable-next-line: no-http-string
    siteOrigin = `http://${siteOrigin}`
  }
  const url = new UrlParse(siteOrigin)

  return url.host
}

/**
 * 返回带协议的origin, 如果原始url不带协议，会加上协议http
 * @param site original site
 * @param sourceURL  source url
 */
export function getSiteOrigin(site: string, sourceURL?: string): string {
  let result = ''
  if (site) {
    result = site
  } else {
    if (sourceURL) {
      const url = new UrlParse(sourceURL)
      result = url.host
    }
  }

  if (result) {
    return normalizeURL(result)
  }

  return result
}

export function normalizeURL(url: string): string {
  if (!url) {
    return ''
  }
  // tslint:disable-next-line: no-http-string
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  } else {
    // tslint:disable-next-line: no-http-string
    return `http://${url}`
  }
}
